package com.scoremg.service.impl;


import java.util.Date;
import java.util.List;

import com.scoremg.entity.contants.Constants;
import com.scoremg.entity.dto.AddUserInfoDto;
import com.scoremg.entity.dto.WebSessionUserDto;
import com.scoremg.entity.enums.ResponseCodeEnum;
import com.scoremg.entity.enums.RoleTypeEnums;
import com.scoremg.entity.po.CourseSelectInfo;
import com.scoremg.entity.po.UserInfo;

import com.scoremg.entity.query.*;

import com.scoremg.entity.vo.PaginationResultVO;

import com.scoremg.exception.BusinessException;
import com.scoremg.mappers.CourseSelectInfoMapper;
import com.scoremg.service.UserInfoService;

import com.scoremg.util.CopyTools;
import com.scoremg.util.StringTools;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.scoremg.mappers.UserInfoMapper;

import com.scoremg.entity.enums.PageSize;
import org.springframework.transaction.annotation.Transactional;


@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService{

	@Resource
	private UserInfoMapper<UserInfo,UserInfoQuery> userInfoMapper;



	@Resource
	private CourseSelectInfoMapper<CourseSelectInfo, CourseSelectInfoQuery> courseSelectInfoMapper;

	/**
	 * 根据条件查询列表
	 */
	public List<UserInfo> findListByParam(UserInfoQuery query) { 
		return this.userInfoMapper.selectList(query);
	}

	/**
	 * 根据条件查询数量
	 */
	public Integer findCountByParam(UserInfoQuery query){
		return this.userInfoMapper.selectCount(query);
	}

	/**
	 * 分页查询
	 */
	public PaginationResultVO<UserInfo> findListByPage(UserInfoQuery  query) { 
		int count = this.findCountByParam(query);
		int pageSize = query.getPageSize()==null?PageSize.SIZE15.getSize():query.getPageSize();
		SimplePage page = new SimplePage(query.getPageNo(),count,pageSize);
		query.setSimplePage(page);
		List<UserInfo> list = this.findListByParam(query);
		return new PaginationResultVO(count,page.getPageSize(),page.getPageNo(),page.getPageTotal(),list);
	}

	/**
	 * 新增
	 */
	public Integer add(UserInfo bean) { 
		return this.userInfoMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	public Integer addBatch(List<UserInfo> listBean) { 
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	public Integer addOrUpdateBatch(List<UserInfo> listBean) { 
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.userInfoMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 根据UserId查询
	 */
	public UserInfo getUserInfoByUserId(String userId) { 
		return this.userInfoMapper.selectByUserId(userId);
	}

	/**
	 * 根据UserId更新
	 */
	public Integer updateUserInfoByUserId(UserInfo bean, String userId) { 
		return this.userInfoMapper.updateByUserId(bean,userId);
	}

	/**
	 * 根据UserId删除
	 */
	@Transactional(rollbackFor = Exception.class)
	public Integer deleteUserInfoByUserId(String userId) {
		UserInfo dbUserInfo = userInfoMapper.selectByUserId(userId);
		if (dbUserInfo == null) {
			throw new BusinessException(Constants.DELETE_ERROR_NOT_EXIST);
		}



		// 2. 删除选课表
		CourseSelectInfoQuery courseSelectInfoQuery = new CourseSelectInfoQuery();
		courseSelectInfoQuery.setStudentId(userId);
		courseSelectInfoQuery.setCourseId(null);
		courseSelectInfoMapper.deleteByParam(courseSelectInfoQuery);

		// 3.删除学生信息
		return this.userInfoMapper.deleteByUserId(userId);
	}

	/**
	 * 根据Eamil查询
	 */
	public UserInfo getUserInfoByEamil(String email) {
		return this.userInfoMapper.selectByEmail(email);
	}

	/**
	 * 根据Eamil更新
	 */
	public Integer updateUserInfoByEamil(UserInfo bean, String eamil) { 
		return this.userInfoMapper.updateByEmail(bean,eamil);
	}

	/**
	 * 根据Eamil删除
	 */
	public Integer deleteUserInfoByEamil(String eamil) { 
		return this.userInfoMapper.deleteByEmail(eamil);
	}

	/**
	 * 根据StuJobNo查询
	 */
	public UserInfo getUserInfoByStuJobNo(String stuJobNo) { 
		return this.userInfoMapper.selectByStuJobNo(stuJobNo);
	}

	/**
	 * 根据StuJobNo更新
	 */
	public Integer updateUserInfoByStuJobNo(UserInfo bean, String stuJobNo) { 
		return this.userInfoMapper.updateByStuJobNo(bean,stuJobNo);
	}

	/**
	 * 根据StuJobNo删除
	 */
	public Integer deleteUserInfoByStuJobNo(String stuJobNo) { 
		return this.userInfoMapper.deleteByStuJobNo(stuJobNo);
	}

	/**
	 * 根据Username查询
	 */
	public UserInfo getUserInfoByUsername(String username) { 
		return this.userInfoMapper.selectByUsername(username);
	}

	/**
	 * 根据Username更新
	 */
	public Integer updateUserInfoByUsername(UserInfo bean, String username) { 
		return this.userInfoMapper.updateByUsername(bean,username);
	}

	/**
	 * 根据Username删除
	 */
	public Integer deleteUserInfoByUsername(String username) { 
		return this.userInfoMapper.deleteByUsername(username);
	}

	/**
	 * 根据Phone查询
	 */
	public UserInfo getUserInfoByPhone(String phone) { 
		return this.userInfoMapper.selectByPhone(phone);
	}

	/**
	 * 根据Phone更新
	 */
	public Integer updateUserInfoByPhone(UserInfo bean, String phone) { 
		return this.userInfoMapper.updateByPhone(bean,phone);
	}

	/**
	 * 根据Phone删除
	 */
	public Integer deleteUserInfoByPhone(String phone) { 
		return this.userInfoMapper.deleteByPhone(phone);
	}


	/**
	 * 登录
	 * @param account 账号信息
	 * @param password 密码
	 * @return WebSessionUserDto
	 */
	@Override
	public WebSessionUserDto login(String account, String password,Integer roleType) {

		// 如果登陆的角色类型错误
		RoleTypeEnums typeEnums = RoleTypeEnums.getByType(roleType);

		if (typeEnums == null) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		UserInfo userInfo = userInfoMapper.selectByUsername(account);
		if (userInfo == null) {
			userInfo=userInfoMapper.selectByStuJobNo(account);
		}
		if (userInfo==null){
			throw new BusinessException(Constants.LOGIN_ERROR_ACCOUNT_UNEXIST);
		}

		// 1.校验密码
		if (!StringTools.encodeByMD5(password).equalsIgnoreCase(userInfo.getPassword())) {
			throw new BusinessException(Constants.LOGIN_ERROR_PASS_ERROR);
		}

		//2. 校验角色登录类型
		if (!userInfo.getRoleType().equals(roleType)){
			throw new BusinessException(Constants.LOGIN_ERROR_ACCOUNT_UNEXIST);
		}

		WebSessionUserDto sessionUserDto = new WebSessionUserDto();
		sessionUserDto.setUserId(userInfo.getUserId());
		sessionUserDto.setRoleType(userInfo.getRoleType());
		sessionUserDto.setUserName(userInfo.getUsername());
		return sessionUserDto;
	}

	/**
	 * 保存用户信息
	 * @param bean 用户信息
	 */
	@Override
	public void saveInfo(AddUserInfoDto bean) {
		// 校验角色类型
		RoleTypeEnums typeEnums = RoleTypeEnums.getByType(bean.getRoleType());
		if (typeEnums == null) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		// 查询数据库
		UserInfo dbUserInfo = null;
		if (bean.getUserId()!=null&&bean.getStuJobNo()!=null) {
			dbUserInfo = this.userInfoMapper.selectByStuJobNo(bean.getStuJobNo());
		}
		UserInfo userInfo = CopyTools.copy(bean, UserInfo.class);
		// 新增 学号不能重复 修改也不能重复 除了查询到的userId!= bean.getUserId
		if((bean.getUserId()==null&&dbUserInfo!=null)||(bean.getUserId()!=null&&dbUserInfo!=null&&!dbUserInfo.getUserId().equals(bean.getUserId()))) {
			throw new BusinessException("用户信息重复，请重试");
		}

		if (!StringTools.isEmpty(bean.getUserId())) {// 保存
			this.updateUserInfoByUserId(userInfo, bean.getUserId());
		}else {
			String userId=StringTools.getRandomString(Constants.LENGTH_12);
			userInfo.setUserId(userId);
			userInfo.setCreateTime(new Date());
			userInfoMapper.insert(userInfo);
		}
	}

	/**
	 * 加载用户详细信息
	 * @param userId 用户id
	 * @return
	 */
	@Override
	public UserInfo loadUserInfoDetail(String userId) {
		UserInfo userInfo = userInfoMapper.selectByUserId(userId);

		if (userInfo==null) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}

		return userInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delInfoBatch(String[] idArray) {
		for (String id : idArray) {
			deleteUserInfoByUserId(id);
		}
	}
}